#include <Rcpp.h>
using namespace Rcpp;
//Model for GIGANTEA (Nagano et al. 2012)
//Time in input starts from 01:01 of the first day and ends at 01:00 of the fourth day.

//parameter constrains:
//0 < pl < 1440
//0 < os < 1440
//0 < ol < 1440

// [[Rcpp::export]]
NumericVector GIGANTEA_cpp(NumericVector input, NumericVector freevec, NumericVector para)
{
  int Ns, Nt, s, t, k;
  double a, b, pl, th, os, ol, Et;
  
  Ns = freevec(0);
  Nt = freevec(1);
  NumericVector output(Ns);
  NumericVector open(Nt);

  a = para(0);
  b = para(1)/1000.0;
  pl = round(para(2));
  th = para(3);
  os = round(para(4)) - 61.0;
  ol = round(para(5));
  
  for(t = os; t<=(os+ol); ++t)
  {
    open[t] = 1.0;
    open[t + 1440] = 1.0;
    open[t + 2880] = 1.0;
    if(t + 4320 < Nt)
      open[t + 4320] = 1.0;
  }
  
  for(s = 0; s<Ns; ++s)
  {
    t = input(s) - 1;
    Et = 0.0;
    for(k = t - pl; k<=t; ++k)
      if(input(Ns+k)>th && open(k)==1.0)
        Et += input(Ns+k) - th;
    output(s) = a + b * Et;
  }
  
  return output;
}



